<?php

/** Zend_Controller_Action */
require_once ROOT_PATH . '/library/Soooner/Controller/WebAction.php';
require_once ROOT_PATH . '/library/Common/Sphinx/sphinxapi.php';

class NotifyController extends Soooner_Web_Controller_Action
{
	public function init()
    {
        /* Initialize action controller here */
    	$this->initDzTemplate();    	
    }
    public function touchAction(){
    	$options = $GLOBALS['application']->getOptions();
    	$minicmdpath = $options["minicmdpath"];//命令路径
    	$signal = intval($this->_getParam('signal'));
    	if($signal>64||$signal<35)return false;
    	if(!file_exists($minicmdpath."minicmd.pid")){
    		exec("nohup php ".$minicmdpath."minicmd.php & \n\n");
    	}
    	$pid = file_get_contents($minicmdpath."minicmd.pid");
        exec("ps -p $pid |grep $pid|wc -l",$n);
        if($n[0]==0){
            exec("nohup php ".$minicmdpath."minicmd.php & \n\n");
        }
    	if(function_exists("posix_kill")){
    		posix_kill($pid, $signal);
    		return true;
    	}
    	return false;
    }
    //受控端执行命令
    public function cmdAction(){
    	$t=$this->_getParam('t');//命令类型lvsc,lvss
    	$ip=$this->_getParam('ip');//受控端ip 如192.168.1.92
    	switch($t)
    	{
    		case "lvsc"://lvs客户端激活
    			$vip=$this->_getParam('vip');//输入参数
    			if(strpos($vip,":")>0)
    				$vip=substr($vip,0,strpos($vip,":"));//删除端口信息
    			if($this->isip($vip)){//判断参数格式
    				$cmdarray=array(
    				"/sbin/ifconfig lo:0 $vip broadcast $vip netmask 255.255.255.255 up",
    				"/sbin/route add -host $vip dev lo:0",
    				"echo \"1\" >/proc/sys/net/ipv4/conf/lo/arp_ignore",
    				"echo \"2\" >/proc/sys/net/ipv4/conf/lo/arp_announce",
    				"echo \"1\" >/proc/sys/net/ipv4/conf/all/arp_ignore",
    				"echo \"2\" >/proc/sys/net/ipv4/conf/all/arp_announce",
    				"sysctl -p"
    				);
    			}
    			break;
    		case "lvss"://lvs配置文件上传并刷新
    			$cid=intval($this->_getParam('cid'));//输入参数
    			$controller=$this->_configs["controller"];//控制端ip地址
    			if($this->isip($controller)){//判断参数格式
    				$cmdarray=array(
    				"wget http://$controller/iiface/lvscnf/cid/$cid -O /etc/keepalived/keepalived.conf",
    				"/etc/init.d/keepalived restart",
    				);
    			}
    			break;
    		default:
    			break;    			
    	}
    	$cmdmain=implode("\n",$cmdarray);
    	echo $cmdmain;
    	echo "#".$this->sshcmd($ip, $cmdmain)."#";
    }
	//通过 ssh远程执行命令
    private function sshcmd($ip,$cmdmain){
    	$cmdheader="ssh bjswaxkjfzyxgs@$ip /bin/sh <<\EOF\ncd ~\nsource .bash_profile\n";
    	$cmdfooter="\nEOF\n";
    	$cmd=$cmdheader.$cmdmain.$cmdfooter;
    	system($cmd,$result);
    	return $result;
    }
    //判断参数是否为ip地址
    private function isip($ip){
    	return ereg("^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$" , $ip);
    }
    public function testAction(){
    	$vip="1.2.3.4:12";//输入参数
    	$vip=substr($vip,0,strpos($vip,":"));
    	echo $vip;
    }
}